//
// Created by 李光辉 on 2021/1/1.
//

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

//Global variable: accessible to all threads
int thread_count;
void* Hello(void* rank); //thread function


int main(int argc, char* argv[])
{
    long thread; //use long in case of a 64-bit system
    pthread_t* thread_handles;

    //get numbers of threads from command line
    thread_count = strtol(argv[1], NULL, 10);
    thread_handles = malloc(thread_count*sizeof(pthread_t));


    for(thread = 0; thread < thread_count; thread++)
        pthread_create(&thread_handles[thread], NULL, Hello, (void *)thread);
    printf("Hello from the main thread\n");

    for(thread = 0; thread < thread_count; thread++)
        pthread_join(thread_handles[thread],NULL);

    free(thread_handles);
    return 0;
}


void* Hello(void* rank)
{
    long my_rank = (long) rank;
    printf("Hello from thread %ld of %d\n", my_rank, thread_count);
    return NULL;
}


/*
 编译：gcc  -g -Wall -o pth_hello 4.1\ pth_hello.c -lpthread
 执行： ./pth_hello 4
*/